package com.jucai.pppeiyouclient.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.base.BaseActivity;
import com.jucai.pppeiyouclient.base.PermissionListener;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.LogUtils;

import java.util.List;

public class AddressSelectActivity extends BaseActivity {
    private static final String TAG = "AddressSelectActivity : ";
    private MapView mapView;
    private BaiduMap baiduMap;
    private LocationClient mLocationClient;
    private double latitude = 0;
    private double longitude = 0;
    private String locAdd = "";
    private TextView tv_address;

    private View addressSelectSearch_searchLl;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_address_select);
        mapView = (MapView) findViewById(R.id.search_map);
        tv_address = (TextView) findViewById(R.id.tv_address);
        addressSelectSearch_searchLl = findViewById(R.id.addressSelectSearch_searchLl);

    }

    @Override
    protected void initData() {
        mLocationClient = new LocationClient(this);
        mLocationClient.registerLocationListener(new CityLocationListener());
        skipPermission();

    }

    @Override
    protected void loadNetData() {

    }

    private void skipPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            BaseActivity.onRuntimePermissionRequest(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE}, new PermissionListener() {
                @Override
                public void onGranted() {
                    initLocation();
                }

                @Override
                public void onDenied(List<String> deniedPermissions) {
                    for (String p : deniedPermissions) {
                        Toast.makeText(AddressSelectActivity.this,
                                p + "权限被拒绝，将会导致无法定位，请前往权限管理打开", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {
            initLocation();
        }
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setLocationNotify(false);
        option.setOpenGps(true);
        option.setAddrType("all");
        mLocationClient.setLocOption(option);
        startLocation();
    }

    /**
     * 添加标记
     */

    private void addMark() {
        baiduMap.clear();
        //定义Maker坐标点
        LatLng point = new LatLng(latitude, longitude);
        //构建Marker图标  ，这里可以自己替换
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.icon_biaoji);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap)
                .zIndex(12)
                .draggable(true);
        //在地图上添加Marker，并显示

        baiduMap.addOverlay(option);

        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(point);//使输入的点位于地图中心
        baiduMap.setMapStatus(u);

    }


    private void startLocation() {
        if (mLocationClient != null && mLocationClient.isStarted()) {
            mLocationClient.stop();
            mLocationClient.start();
        } else if (mLocationClient != null) {
            mLocationClient.start();
        }
    }

    private void location(double latitude, double longitude) {
        try {
            BaiduMap mBaidumap = mapView.getMap();
            LatLng cenpt = new LatLng(latitude, longitude);
            MapStatus mMapStatus = new MapStatus.Builder()
                    .target(cenpt)
                    .zoom(18)
                    .build();
            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
            mBaidumap.setMapStatus(mMapStatusUpdate);
            tv_address.setText(locAdd);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        addMark();
    }


    @Override
    protected void setListener() {
        findViewById(R.id.common_back).setOnClickListener(this);
        findViewById(R.id.common_sure).setOnClickListener(this);
        addressSelectSearch_searchLl.setOnClickListener(this);
        baiduMap = mapView.getMap();
        baiduMap.setOnMapClickListener(onMapClickListener);
        baiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                latitude = mapStatus.target.latitude;
                longitude = mapStatus.target.longitude;

                GeoCoder geoCoder = GeoCoder.newInstance();
                geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(mapStatus.target));
                geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

                    }

                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                        String address = reverseGeoCodeResult.getAddress();
                        if (!TextUtils.isEmpty(address)) {
                            locAdd = address;
                            tv_address.setText(locAdd);
                        }
                    }
                });
            }
        });
    }

    /**
     * \
     * 点击地图添加窗口地址(需自定义view  )
     */
    private void addWindow() {
        //创建InfoWindow展示的view
        TextView button = new TextView(getApplicationContext());
        button.setPadding(10, 10, 10, 10);
        button.setTextSize(14);
        button.setTextColor(AddressSelectActivity.this.getResources().getColor(R.color.black));
        button.setBackgroundColor(AddressSelectActivity.this.getResources().getColor(R.color.white));
        button.setText(locAdd);
        //定义用于显示该InfoWindow的坐标点
        LatLng pt = new LatLng(latitude, longitude);
        //创建InfoWindow , 传入 view， 地理坐标， y 轴偏移量
        InfoWindow mInfoWindow = new InfoWindow(button, pt, -100);
        //显示InfoWindow
        baiduMap.showInfoWindow(mInfoWindow);

    }

    private BaiduMap.OnMapClickListener onMapClickListener = new BaiduMap.OnMapClickListener() {

        public void onMapClick(LatLng point) {

        }

        public boolean onMapPoiClick(MapPoi poi) {
            LatLng latLng = poi.getPosition();
            latitude = latLng.latitude;
            longitude = latLng.longitude;
            locAdd = poi.getName().replace("\\", "");
            LogUtils.e(TAG + "地理信息onMapPoiClick：" + latitude + "," + longitude + "," + locAdd);
            location(latitude, longitude);
            return false;
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                ActivityCollector.removeActivity(this);
                break;

            case R.id.common_sure:
                Intent intent = new Intent();
                intent.putExtra("latitude", latitude);
                intent.putExtra("longitude", longitude);
                intent.putExtra("loc_address", locAdd);
                setResult(RESULT_OK, intent);
                ActivityCollector.removeActivity(this);
                break;
            case R.id.addressSelectSearch_searchLl: {
                Intent intent1 = new Intent(AddressSelectActivity.this, AddressSelectSearchActivity.class);
                startActivityForResult(intent1, 1002);
            }
            break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null && mLocationClient.isStarted()) {
            mLocationClient.stop();
            mLocationClient = null;
        }
        mapView.onDestroy();
    }

    public class CityLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (mLocationClient != null && mLocationClient.isStarted()) {
                mLocationClient.stop();
            }
            latitude = bdLocation.getLatitude();
            longitude = bdLocation.getLongitude();
            locAdd = bdLocation.getAddrStr();
            LogUtils.e(TAG + "定位结束 onReceiveLocation：" + latitude + "," + longitude);
            location(latitude, longitude);
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {
            LogUtils.e(TAG + "定位结束 onConnectHotSpotMessage：" + s + "," + i);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1002 && resultCode == Activity.RESULT_OK) {
            latitude = data.getDoubleExtra("latitude", 0);
            longitude = data.getDoubleExtra("longitude", 0);
            locAdd = data.getStringExtra("address");

            location(latitude, longitude);

        }

    }
}
